package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.PageBean;
import com.itheima.dto.EmpExprDto;
import com.itheima.dto.EmpLoginDto;
import com.itheima.dto.EmpQueryDto;
import com.itheima.dto.EmpUpdateDto;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import com.itheima.vo.EmpLoginVo;
import com.itheima.vo.EmpVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    EmpMapper empMapper;
    @Autowired
    EmpExprMapper empExprMapper;

    @Override
    public PageBean pageQuery(EmpQueryDto dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<EmpVo> page = (Page<EmpVo>) empMapper.query(dto);

        long total = page.getTotal();
        List<EmpVo> result = page.getResult();

        PageBean pageBean = new PageBean(total, result);

       /* pageBean.setTotal(455L);
        List<Emp> list = empMapper.selectAll();
        pageBean.setRows(list);*/

        return pageBean;
    }

    @Override
    @Transactional
    public void add(EmpExprDto dto) {

        Emp emp = new Emp();
        BeanUtils.copyProperties(dto, emp);
        emp.setPassword("123445");
        String s = DigestUtil.md5Hex(emp.getPassword());
        emp.setPassword(s);
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);

        List<EmpExpr> exprList = dto.getExprList();
        exprList.forEach(empExpr -> {
            empExpr.setEmpId(emp.getId());
            empExprMapper.insert(empExpr);
        });
    }

    @Override
    public EmpVo selectid(Integer id) {
        EmpVo vo = new EmpVo();
        List<EmpExpr> vos = empExprMapper.selectid(id);
        Emp selectid = empMapper.selectid(id);
        BeanUtils.copyProperties(selectid, vo);
        vo.setExprList(vos);
        return vo;
    }

    @Override
    @Transactional
    public void update(EmpExprDto dto) {
        Emp emp = new Emp();
        BeanUtils.copyProperties(dto, emp);
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updata(emp);

        List<EmpExpr> exprList = dto.getExprList();
        empExprMapper.deleteid(emp.getId());
        exprList.forEach(empExpr -> {
            empExpr.setEmpId(emp.getId());
            empExprMapper.insert(empExpr);
        });
    }

    @Override
    @Transactional
    public void deleteid(List<Integer> id) {
        id.forEach(i -> {
            empMapper.deleteid(i);
            empExprMapper.deleteid(i);
        });
    }

    @Override
    public List<Emp> selectall() {
        List<Emp> list = empMapper.selectAll();
        return list;
    }

    @Override
    public EmpLoginVo emplogin(EmpLoginDto dto) {
        Emp emp = empMapper.getbyusername(dto.getUsername());
        if (emp == null) {
            throw new RuntimeException("用户名不存在");
        }
        String s = DigestUtil.md5Hex(dto.getPassword());

        if (!StrUtil.equals(emp.getPassword(), s)) {
            throw new RuntimeException("密码错误");
        }

        /*if (!StrUtil.equals(emp.getPassword(), dto.getPassword())) {
            throw new RuntimeException("密码错误");
        }*/

       /* String key = "1234567";

        HashMap hashMap = new HashMap();
        hashMap.put("id", emp.getId());
        String compact = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key)
                .setClaims(hashMap)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .compact();*/
        Map<String, Object> map = new HashMap<>();
        map.put("id", emp.getId());

        String jwt = JwtUtils.createJwt(map);

        return EmpLoginVo.builder()
                .id(emp.getId())
                .name(emp.getName())
                .username(emp.getUsername())
                .token(jwt)
                .build();
    }

    @Override
    public void deletedeptid(Integer id) {
        empMapper.deletedeptid(id);
    }

    @Override
    public void empupdate(EmpUpdateDto dto) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String id = JwtUtils.Jwt(token).get("id").toString();

        Emp emp = empMapper.selectid(Integer.valueOf(id));

        String s1 = DigestUtil.md5Hex(dto.getPassword());
        //d41d8cd98f00b204e9800998ecf8427e
        System.out.println(s1);
        if (!StrUtil.equals(emp.getPassword(), s1)) {
            throw new RuntimeException("原始密码错误，请重新输入");
        }

        String s = DigestUtil.md5Hex(dto.getNewpassword());
        emp.setPassword(s);
        empMapper.updata(emp);

    }
}
